package com.linan.intercepter;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        List<String> list = Arrays.asList("/api/common/login","/api/pdf-manage/query-by-uuid");
        if (CollectionUtils.contains(list.iterator(), uri)) {
            return true;
        }

        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            wreteReturnMessage(response);
            return false;
        }
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName()+cookie.getValue());
            System.out.println(cookie.getName().equals("username"));
            if(cookie.getName().equals("username")&& !cookie.getName().isEmpty()){
                return true;
            }
        }
        wreteReturnMessage(response);
        return false;
    }

    private void wreteReturnMessage(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;chaset=utf-8");
        PrintWriter writer = response.getWriter();
        response.setStatus(403);

        writer.write("{message:\"登录失效\",success:false}");
        writer.close();
    }
}
